Search Insert Position

Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it > would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.

  • [1,3,5,6], 5 → 2
  • [1,3,5,6], 2 → 1
  • [1,3,5,6], 7 → 4
  • [1,3,5,6], 0 → 0

题目大意:给定排好序的数组和目标值,返回目标值的索引,若不存在,返回可以插入的位置

题目难度:Medium

/**
 * Created by gzdaijie on 16/5/20
 */
public class Solution {
    public int searchInsert(int[] nums, int target) {
        int len = nums.length;
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) return mid;

            if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
}
gzdaijie            updated 2016-05-20 18:02:53

results matching ""

    No results matching ""